//
//  HybridConfig.swift
//  mall-ios
//
//  Created by Meak Tsui on 2018/11/26.
//  Copyright © 2018 Meak Tsui. All rights reserved.
//

import Foundation

public class MTHybridConfig {
    public init() {}
    
    weak var hybrid:MTHybrid? {
        didSet{
            producers.forEach { (arg) in
                var producer = arg.value
                producer.hybrid = self.hybrid
            }
        }
    }
    public var appName:String?
    public var actionHandlers = [String:MTEventHandler]()
    public var producers = [String:MTEventProducer]()
    public var whiteUrlList:[String] = []  //网址白名单，白名单内的网址才可以使用hybrid api
    public var isOpenWhiteList:Bool = false //是否开启白名单过滤功能
    public var custumerUA:String?
    
    public func register(handler:MTEventHandler,force:Bool = false) {
        let key = getKey(from:handler.ns,and: handler.action)
        if !force, let _ = actionHandlers[key] {
            return
        }
        actionHandlers[key] = handler
    }
    
    public func register(handlers:[MTEventHandler],force:Bool = false) {
        handlers.forEach { (handler) in
            register(handler: handler, force: force)
        }
    }
    
    public func register(producer: inout MTEventProducer,force:Bool = false) {
        let key = getKey(from:producer.ns,and: producer.event)
        if !force, let _ = producers[key] {
            return
        }
        producer.hybrid = self.hybrid
        producers[key] = producer
    }
    
    public func register(producers: [MTEventProducer],force:Bool = false) {
        for var producer in producers {
            register(producer: &producer, force: force)
        }
    }
    
    public func getHandler(ns:Ns,action:Api) -> MTEventHandler {
        let key = getKey(from:ns,and:action)
        return actionHandlers[key] ?? MTEmptyEventHandler(ns: ns, action: action)
    }
    
    public func getProducer(ns:Ns,action:Api) -> MTEventProducer? {
        let key = getKey(from:ns,and:action)
        return producers[key]
    }
    
    fileprivate func getKey(from:Ns,and:Api) -> String {
        return "\(from.rawValue)_\(and.rawValue)"
    }
    
    
    public static func `default`()  -> MTHybridConfig {
        let config = MTHybridConfig()
        return config
    }
}
